<!-- HTML header for doxygen 1.8.6-->
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<meta name="generator" content="Doxygen 1.8.13"/>
<title>OpenCV: Creating Bounding boxes and circles for contours</title>
<link href="../../opencv.ico" rel="shortcut icon" type="image/x-icon" />
<link href="../../tabs.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="../../jquery.js"></script>
<script type="text/javascript" src="../../dynsections.js"></script>
<script type="text/javascript" src="../../tutorial-utils.js"></script>
<link href="../../search/search.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="../../search/searchdata.js"></script>
<script type="text/javascript" src="../../search/search.js"></script>
<script type="text/x-mathjax-config">
  MathJax.Hub.Config({
    extensions: ["tex2jax.js", "TeX/AMSmath.js", "TeX/AMSsymbols.js"],
    jax: ["input/TeX","output/HTML-CSS"],
});
//<![CDATA[
MathJax.Hub.Config(
{
  TeX: {
      Macros: {
          matTT: [ "\\[ \\left|\\begin{array}{ccc} #1 & #2 & #3\\\\ #4 & #5 & #6\\\\ #7 & #8 & #9 \\end{array}\\right| \\]", 9],
          fork: ["\\left\\{ \\begin{array}{l l} #1 & \\mbox{#2}\\\\ #3 & \\mbox{#4}\\\\ \\end{array} \\right.", 4],
          forkthree: ["\\left\\{ \\begin{array}{l l} #1 & \\mbox{#2}\\\\ #3 & \\mbox{#4}\\\\ #5 & \\mbox{#6}\\\\ \\end{array} \\right.", 6],
          forkfour: ["\\left\\{ \\begin{array}{l l} #1 & \\mbox{#2}\\\\ #3 & \\mbox{#4}\\\\ #5 & \\mbox{#6}\\\\ #7 & \\mbox{#8}\\\\ \\end{array} \\right.", 8],
          vecthree: ["\\begin{bmatrix} #1\\\\ #2\\\\ #3 \\end{bmatrix}", 3],
          vecthreethree: ["\\begin{bmatrix} #1 & #2 & #3\\\\ #4 & #5 & #6\\\\ #7 & #8 & #9 \\end{bmatrix}", 9],
          cameramatrix: ["#1 = \\begin{bmatrix} f_x & 0 & c_x\\\\ 0 & f_y & c_y\\\\ 0 & 0 & 1 \\end{bmatrix}", 1],
          distcoeffs: ["(k_1, k_2, p_1, p_2[, k_3[, k_4, k_5, k_6 [, s_1, s_2, s_3, s_4[, \\tau_x, \\tau_y]]]]) \\text{ of 4, 5, 8, 12 or 14 elements}"],
          distcoeffsfisheye: ["(k_1, k_2, k_3, k_4)"],
          hdotsfor: ["\\dots", 1],
          mathbbm: ["\\mathbb{#1}", 1],
          bordermatrix: ["\\matrix{#1}", 1]
      }
  }
}
);
//]]>
</script><script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.0/MathJax.js"></script>
<link href="../../doxygen.css" rel="stylesheet" type="text/css" />
<link href="../../stylesheet.css" rel="stylesheet" type="text/css"/>
</head>
<body>
<div id="top"><!-- do not remove this div, it is closed by doxygen! -->
<div id="titlearea">
<!--#include virtual="/google-search.html"-->
<table cellspacing="0" cellpadding="0">
 <tbody>
 <tr style="height: 56px;">
  <td id="projectlogo"><img alt="Logo" src="../../opencv-logo-small.png"/></td>
  <td style="padding-left: 0.5em;">
   <div id="projectname">OpenCV
   &#160;<span id="projectnumber">4.5.2</span>
   </div>
   <div id="projectbrief">Open Source Computer Vision</div>
  </td>
 </tr>
 </tbody>
</table>
</div>
<!-- end header part -->
<!-- Generated by Doxygen 1.8.13 -->
<script type="text/javascript">
var searchBox = new SearchBox("searchBox", "../../search",false,'Search');
</script>
<script type="text/javascript" src="../../menudata.js"></script>
<script type="text/javascript" src="../../menu.js"></script>
<script type="text/javascript">
$(function() {
  initMenu('../../',true,false,'search.php','Search');
  $(document).ready(function() { init_search(); });
});
</script>
<div id="main-nav"></div>
<!-- window showing the filter options -->
<div id="MSearchSelectWindow"
     onmouseover="return searchBox.OnSearchSelectShow()"
     onmouseout="return searchBox.OnSearchSelectHide()"
     onkeydown="return searchBox.OnSearchSelectKey(event)">
</div>

<!-- iframe showing the search results (closed by default) -->
<div id="MSearchResultsWindow">
<iframe src="javascript:void(0)" frameborder="0" 
        name="MSearchResults" id="MSearchResults">
</iframe>
</div>

<div id="nav-path" class="navpath">
  <ul>
<li class="navelem"><a class="el" href="../../d9/df8/tutorial_root.html">OpenCV Tutorials</a></li><li class="navelem"><a class="el" href="../../d7/da8/tutorial_table_of_content_imgproc.html">Image Processing (imgproc module)</a></li>  </ul>
</div>
</div><!-- top -->
<div class="header">
  <div class="headertitle">
<div class="title">Creating Bounding boxes and circles for contours </div>  </div>
</div><!--header-->
<div class="contents">
<div class="textblock"><p><b>Prev Tutorial:</b> <a class="el" href="../../d7/d1d/tutorial_hull.html">Convex Hull</a></p>
<p><b>Next Tutorial:</b> <a class="el" href="../../de/d62/tutorial_bounding_rotated_ellipses.html">Creating Bounding rotated boxes and ellipses for contours</a></p>
<table class="doxtable">
<tr>
<th align="right"></th><th align="left"></th></tr>
<tr>
<td align="right">Original author </td><td align="left">Ana Huamán </td></tr>
<tr>
<td align="right">Compatibility </td><td align="left">OpenCV &gt;= 3.0 </td></tr>
</table>
<h2>Goal </h2>
<p>In this tutorial you will learn how to:</p>
<ul>
<li>Use the OpenCV function <a class="el" href="../../d3/dc0/group__imgproc__shape.html#ga103fcbda2f540f3ef1c042d6a9b35ac7">cv::boundingRect</a></li>
<li>Use the OpenCV function <a class="el" href="../../d3/dc0/group__imgproc__shape.html#ga8ce13c24081bbc7151e9326f412190f1">cv::minEnclosingCircle</a></li>
</ul>
<h2>Theory </h2>
<h2>Code </h2>
 <div class='newInnerHTML' title='cpp' style='display: none;'>C++</div><div class='toggleable_div label_cpp' style='display: none;'><p> This tutorial code's is shown lines below. You can also download it from <a href="https://github.com/opencv/opencv/tree/master/samples/cpp/tutorial_code/ShapeDescriptors/generalContours_demo1.cpp">here</a> </p><div class="fragment"><div class="line"></div><div class="line"><span class="preprocessor">#include &quot;<a class="code" href="../../d6/d87/imgcodecs_8hpp.html">opencv2/imgcodecs.hpp</a>&quot;</span></div><div class="line"><span class="preprocessor">#include &quot;<a class="code" href="../../d4/dd5/highgui_8hpp.html">opencv2/highgui.hpp</a>&quot;</span></div><div class="line"><span class="preprocessor">#include &quot;<a class="code" href="../../d1/d4f/imgproc_2include_2opencv2_2imgproc_8hpp.html">opencv2/imgproc.hpp</a>&quot;</span></div><div class="line"><span class="preprocessor">#include &lt;iostream&gt;</span></div><div class="line"></div><div class="line"><span class="keyword">using namespace </span><a class="code" href="../../d2/d75/namespacecv.html">cv</a>;</div><div class="line"><span class="keyword">using namespace </span>std;</div><div class="line"></div><div class="line"><a class="code" href="../../d3/d63/classcv_1_1Mat.html">Mat</a> src_gray;</div><div class="line"><span class="keywordtype">int</span> thresh = 100;</div><div class="line"><a class="code" href="../../d1/dd6/classcv_1_1RNG.html">RNG</a> rng(12345);</div><div class="line"></div><div class="line"><span class="keywordtype">void</span> thresh_callback(<span class="keywordtype">int</span>, <span class="keywordtype">void</span>* );</div><div class="line"></div><div class="line"><span class="keywordtype">int</span> main( <span class="keywordtype">int</span> argc, <span class="keywordtype">char</span>** argv )</div><div class="line">{</div><div class="line">    <a class="code" href="../../d0/d2e/classcv_1_1CommandLineParser.html">CommandLineParser</a> parser( argc, argv, <span class="stringliteral">&quot;{@input | stuff.jpg | input image}&quot;</span> );</div><div class="line">    <a class="code" href="../../d3/d63/classcv_1_1Mat.html">Mat</a> src = <a class="code" href="../../d4/da8/group__imgcodecs.html#ga288b8b3da0892bd651fce07b3bbd3a56">imread</a>( <a class="code" href="../../d6/dba/group__core__utils__samples.html#ga3a33b00033b46c698ff6340d95569c13">samples::findFile</a>( parser.get&lt;<a class="code" href="../../dc/d84/group__core__basic.html#ga1f6634802eeadfd7245bc75cf3e216c2">String</a>&gt;( <span class="stringliteral">&quot;@input&quot;</span> ) ) );</div><div class="line">    <span class="keywordflow">if</span>( src.<a class="code" href="../../d3/d63/classcv_1_1Mat.html#abbec3525a852e77998aba034813fded4">empty</a>() )</div><div class="line">    {</div><div class="line">        cout &lt;&lt; <span class="stringliteral">&quot;Could not open or find the image!\n&quot;</span> &lt;&lt; endl;</div><div class="line">        cout &lt;&lt; <span class="stringliteral">&quot;usage: &quot;</span> &lt;&lt; argv[0] &lt;&lt; <span class="stringliteral">&quot; &lt;Input image&gt;&quot;</span> &lt;&lt; endl;</div><div class="line">        <span class="keywordflow">return</span> -1;</div><div class="line">    }</div><div class="line"></div><div class="line">    <a class="code" href="../../d8/d01/group__imgproc__color__conversions.html#ga397ae87e1288a81d2363b61574eb8cab">cvtColor</a>( src, src_gray, <a class="code" href="../../d8/d01/group__imgproc__color__conversions.html#gga4e0972be5de079fed4e3a10e24ef5ef0a353a4b8db9040165db4dacb5bcefb6ea">COLOR_BGR2GRAY</a> );</div><div class="line">    <a class="code" href="../../d4/d86/group__imgproc__filter.html#ga8c45db9afe636703801b0b2e440fce37">blur</a>( src_gray, src_gray, <a class="code" href="../../dc/d84/group__core__basic.html#ga346f563897249351a34549137c8532a0">Size</a>(3,3) );</div><div class="line"></div><div class="line">    <span class="keyword">const</span> <span class="keywordtype">char</span>* source_window = <span class="stringliteral">&quot;Source&quot;</span>;</div><div class="line">    <a class="code" href="../../d7/dfc/group__highgui.html#ga5afdf8410934fd099df85c75b2e0888b">namedWindow</a>( source_window );</div><div class="line">    <a class="code" href="../../d7/dfc/group__highgui.html#ga453d42fe4cb60e5723281a89973ee563">imshow</a>( source_window, src );</div><div class="line"></div><div class="line">    <span class="keyword">const</span> <span class="keywordtype">int</span> max_thresh = 255;</div><div class="line">    <a class="code" href="../../d7/dfc/group__highgui.html#gaf78d2155d30b728fc413803745b67a9b">createTrackbar</a>( <span class="stringliteral">&quot;Canny thresh:&quot;</span>, source_window, &amp;thresh, max_thresh, thresh_callback );</div><div class="line">    thresh_callback( 0, 0 );</div><div class="line"></div><div class="line">    <a class="code" href="../../d7/dfc/group__highgui.html#ga5628525ad33f52eab17feebcfba38bd7">waitKey</a>();</div><div class="line">    <span class="keywordflow">return</span> 0;</div><div class="line">}</div><div class="line"></div><div class="line"><span class="keywordtype">void</span> thresh_callback(<span class="keywordtype">int</span>, <span class="keywordtype">void</span>* )</div><div class="line">{</div><div class="line">    <a class="code" href="../../d3/d63/classcv_1_1Mat.html">Mat</a> canny_output;</div><div class="line">    <a class="code" href="../../dd/d1a/group__imgproc__feature.html#ga04723e007ed888ddf11d9ba04e2232de">Canny</a>( src_gray, canny_output, thresh, thresh*2 );</div><div class="line"></div><div class="line">    vector&lt;vector&lt;Point&gt; &gt; contours;</div><div class="line">    <a class="code" href="../../d3/dc0/group__imgproc__shape.html#gadf1ad6a0b82947fa1fe3c3d497f260e0">findContours</a>( canny_output, contours, <a class="code" href="../../d3/dc0/group__imgproc__shape.html#gga819779b9857cc2f8601e6526a3a5bc71ab10df56aed56c89a026580adc9431f58">RETR_TREE</a>, <a class="code" href="../../d3/dc0/group__imgproc__shape.html#gga4303f45752694956374734a03c54d5ffa5f2883048e654999209f88ba04c302f5">CHAIN_APPROX_SIMPLE</a> );</div><div class="line"></div><div class="line">    vector&lt;vector&lt;Point&gt; &gt; contours_poly( contours.size() );</div><div class="line">    vector&lt;Rect&gt; boundRect( contours.size() );</div><div class="line">    vector&lt;Point2f&gt;centers( contours.size() );</div><div class="line">    vector&lt;float&gt;radius( contours.size() );</div><div class="line"></div><div class="line">    <span class="keywordflow">for</span>( <span class="keywordtype">size_t</span> i = 0; i &lt; contours.size(); i++ )</div><div class="line">    {</div><div class="line">        <a class="code" href="../../d3/dc0/group__imgproc__shape.html#ga0012a5fdaea70b8a9970165d98722b4c">approxPolyDP</a>( contours[i], contours_poly[i], 3, <span class="keyword">true</span> );</div><div class="line">        boundRect[i] = <a class="code" href="../../d3/dc0/group__imgproc__shape.html#ga103fcbda2f540f3ef1c042d6a9b35ac7">boundingRect</a>( contours_poly[i] );</div><div class="line">        <a class="code" href="../../d3/dc0/group__imgproc__shape.html#ga8ce13c24081bbc7151e9326f412190f1">minEnclosingCircle</a>( contours_poly[i], centers[i], radius[i] );</div><div class="line">    }</div><div class="line"></div><div class="line">    <a class="code" href="../../d3/d63/classcv_1_1Mat.html">Mat</a> drawing = <a class="code" href="../../d3/d63/classcv_1_1Mat.html#a0b57b6a326c8876d944d188a46e0f556">Mat::zeros</a>( canny_output.<a class="code" href="../../d3/d63/classcv_1_1Mat.html#a146f8e8dda07d1365a575ab83d9828d1">size</a>(), <a class="code" href="../../d1/d1b/group__core__hal__interface.html#ga88c4cd9de76f678f33928ef1e3f96047">CV_8UC3</a> );</div><div class="line"></div><div class="line">    <span class="keywordflow">for</span>( <span class="keywordtype">size_t</span> i = 0; i&lt; contours.size(); i++ )</div><div class="line">    {</div><div class="line">        <a class="code" href="../../d1/da0/classcv_1_1Scalar__.html">Scalar</a> color = <a class="code" href="../../dc/d84/group__core__basic.html#ga599fe92e910c027be274233eccad7beb">Scalar</a>( rng.uniform(0, 256), rng.uniform(0,256), rng.uniform(0,256) );</div><div class="line">        <a class="code" href="../../d6/d6e/group__imgproc__draw.html#ga746c0625f1781f1ffc9056259103edbc">drawContours</a>( drawing, contours_poly, (<span class="keywordtype">int</span>)i, color );</div><div class="line">        <a class="code" href="../../d6/d6e/group__imgproc__draw.html#ga07d2f74cadcf8e305e810ce8eed13bc9">rectangle</a>( drawing, boundRect[i].tl(), boundRect[i].br(), color, 2 );</div><div class="line">        <a class="code" href="../../d6/d6e/group__imgproc__draw.html#gaf10604b069374903dbd0f0488cb43670">circle</a>( drawing, centers[i], (<span class="keywordtype">int</span>)radius[i], color, 2 );</div><div class="line">    }</div><div class="line"></div><div class="line">    <a class="code" href="../../d7/dfc/group__highgui.html#ga453d42fe4cb60e5723281a89973ee563">imshow</a>( <span class="stringliteral">&quot;Contours&quot;</span>, drawing );</div><div class="line">}</div></div><!-- fragment -->  </div>  <div class='newInnerHTML' title='java' style='display: none;'>Java</div><div class='toggleable_div label_java' style='display: none;'><p> This tutorial code's is shown lines below. You can also download it from <a href="https://github.com/opencv/opencv/tree/master/samples/java/tutorial_code/ShapeDescriptors/bounding_rects_circles/GeneralContoursDemo1.java">here</a> </p><div class="fragment"><div class="line"><span class="keyword">import</span> java.awt.BorderLayout;</div><div class="line"><span class="keyword">import</span> java.awt.Container;</div><div class="line"><span class="keyword">import</span> java.awt.Image;</div><div class="line"><span class="keyword">import</span> java.util.ArrayList;</div><div class="line"><span class="keyword">import</span> java.util.List;</div><div class="line"><span class="keyword">import</span> java.util.Random;</div><div class="line"></div><div class="line"><span class="keyword">import</span> javax.swing.BoxLayout;</div><div class="line"><span class="keyword">import</span> javax.swing.ImageIcon;</div><div class="line"><span class="keyword">import</span> javax.swing.JFrame;</div><div class="line"><span class="keyword">import</span> javax.swing.JLabel;</div><div class="line"><span class="keyword">import</span> javax.swing.JPanel;</div><div class="line"><span class="keyword">import</span> javax.swing.JSlider;</div><div class="line"><span class="keyword">import</span> javax.swing.event.ChangeEvent;</div><div class="line"><span class="keyword">import</span> javax.swing.event.ChangeListener;</div><div class="line"></div><div class="line"><span class="keyword">import</span> org.opencv.core.Core;</div><div class="line"><span class="keyword">import</span> org.opencv.core.CvType;</div><div class="line"><span class="keyword">import</span> org.opencv.core.Mat;</div><div class="line"><span class="keyword">import</span> org.opencv.core.MatOfPoint;</div><div class="line"><span class="keyword">import</span> org.opencv.core.MatOfPoint2f;</div><div class="line"><span class="keyword">import</span> org.opencv.core.Point;</div><div class="line"><span class="keyword">import</span> org.opencv.core.Rect;</div><div class="line"><span class="keyword">import</span> org.opencv.core.Scalar;</div><div class="line"><span class="keyword">import</span> org.opencv.core.Size;</div><div class="line"><span class="keyword">import</span> org.opencv.highgui.HighGui;</div><div class="line"><span class="keyword">import</span> org.opencv.imgcodecs.Imgcodecs;</div><div class="line"><span class="keyword">import</span> org.opencv.imgproc.Imgproc;</div><div class="line"></div><div class="line"><span class="keyword">class </span>GeneralContours1 {</div><div class="line">    <span class="keyword">private</span> Mat srcGray = <span class="keyword">new</span> Mat();</div><div class="line">    <span class="keyword">private</span> JFrame frame;</div><div class="line">    <span class="keyword">private</span> JLabel imgSrcLabel;</div><div class="line">    <span class="keyword">private</span> JLabel imgContoursLabel;</div><div class="line">    <span class="keyword">private</span> <span class="keyword">static</span> <span class="keyword">final</span> <span class="keywordtype">int</span> MAX_THRESHOLD = 255;</div><div class="line">    <span class="keyword">private</span> <span class="keywordtype">int</span> threshold = 100;</div><div class="line">    <span class="keyword">private</span> Random rng = <span class="keyword">new</span> Random(12345);</div><div class="line"></div><div class="line">    <span class="keyword">public</span> GeneralContours1(<a class="code" href="../../dc/d84/group__core__basic.html#ga1f6634802eeadfd7245bc75cf3e216c2">String</a>[] args) {</div><div class="line">        <a class="code" href="../../dc/d84/group__core__basic.html#ga1f6634802eeadfd7245bc75cf3e216c2">String</a> filename = args.length &gt; 0 ? args[0] : <span class="stringliteral">&quot;../data/stuff.jpg&quot;</span>;</div><div class="line">        Mat src = Imgcodecs.imread(filename);</div><div class="line">        <span class="keywordflow">if</span> (src.empty()) {</div><div class="line">            System.err.println(<span class="stringliteral">&quot;Cannot read image: &quot;</span> + filename);</div><div class="line">            System.exit(0);</div><div class="line">        }</div><div class="line"></div><div class="line">        Imgproc.cvtColor(src, srcGray, Imgproc.COLOR_BGR2GRAY);</div><div class="line">        Imgproc.blur(srcGray, srcGray, <span class="keyword">new</span> <a class="code" href="../../dc/d84/group__core__basic.html#ga346f563897249351a34549137c8532a0">Size</a>(3, 3));</div><div class="line"></div><div class="line">        <span class="comment">// Create and set up the window.</span></div><div class="line">        frame = <span class="keyword">new</span> JFrame(<span class="stringliteral">&quot;Creating Bounding boxes and circles for contours demo&quot;</span>);</div><div class="line">        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);</div><div class="line">        <span class="comment">// Set up the content pane.</span></div><div class="line">        Image img = HighGui.toBufferedImage(src);</div><div class="line">        addComponentsToPane(frame.getContentPane(), img);</div><div class="line">        <span class="comment">// Use the content pane&#39;s default BorderLayout. No need for</span></div><div class="line">        <span class="comment">// setLayout(new BorderLayout());</span></div><div class="line">        <span class="comment">// Display the window.</span></div><div class="line">        frame.pack();</div><div class="line">        frame.setVisible(<span class="keyword">true</span>);</div><div class="line">        update();</div><div class="line">    }</div><div class="line"></div><div class="line">    <span class="keyword">private</span> <span class="keywordtype">void</span> addComponentsToPane(Container pane, Image img) {</div><div class="line">        <span class="keywordflow">if</span> (!(pane.getLayout() instanceof BorderLayout)) {</div><div class="line">            pane.add(<span class="keyword">new</span> JLabel(<span class="stringliteral">&quot;Container doesn&#39;t use BorderLayout!&quot;</span>));</div><div class="line">            <span class="keywordflow">return</span>;</div><div class="line">        }</div><div class="line"></div><div class="line">        JPanel sliderPanel = <span class="keyword">new</span> JPanel();</div><div class="line">        sliderPanel.setLayout(<span class="keyword">new</span> BoxLayout(sliderPanel, BoxLayout.PAGE_AXIS));</div><div class="line"></div><div class="line">        sliderPanel.add(<span class="keyword">new</span> JLabel(<span class="stringliteral">&quot;Canny threshold: &quot;</span>));</div><div class="line">        JSlider slider = <span class="keyword">new</span> JSlider(0, MAX_THRESHOLD, threshold);</div><div class="line">        slider.setMajorTickSpacing(20);</div><div class="line">        slider.setMinorTickSpacing(10);</div><div class="line">        slider.setPaintTicks(<span class="keyword">true</span>);</div><div class="line">        slider.setPaintLabels(<span class="keyword">true</span>);</div><div class="line">        slider.addChangeListener(<span class="keyword">new</span> ChangeListener() {</div><div class="line">            @Override</div><div class="line">            <span class="keyword">public</span> <span class="keywordtype">void</span> stateChanged(ChangeEvent e) {</div><div class="line">                JSlider source = (JSlider) e.getSource();</div><div class="line">                threshold = source.getValue();</div><div class="line">                update();</div><div class="line">            }</div><div class="line">        });</div><div class="line">        sliderPanel.add(slider);</div><div class="line">        pane.add(sliderPanel, BorderLayout.PAGE_START);</div><div class="line"></div><div class="line">        JPanel imgPanel = <span class="keyword">new</span> JPanel();</div><div class="line">        imgSrcLabel = <span class="keyword">new</span> JLabel(<span class="keyword">new</span> ImageIcon(img));</div><div class="line">        imgPanel.add(imgSrcLabel);</div><div class="line"></div><div class="line">        Mat blackImg = Mat.zeros(srcGray.size(), CvType.CV_8U);</div><div class="line">        imgContoursLabel = <span class="keyword">new</span> JLabel(<span class="keyword">new</span> ImageIcon(HighGui.toBufferedImage(blackImg)));</div><div class="line">        imgPanel.add(imgContoursLabel);</div><div class="line"></div><div class="line">        pane.add(imgPanel, BorderLayout.CENTER);</div><div class="line">    }</div><div class="line"></div><div class="line">    <span class="keyword">private</span> <span class="keywordtype">void</span> update() {</div><div class="line">        Mat cannyOutput = <span class="keyword">new</span> Mat();</div><div class="line">        Imgproc.Canny(srcGray, cannyOutput, threshold, threshold * 2);</div><div class="line"></div><div class="line">        List&lt;MatOfPoint&gt; contours = <span class="keyword">new</span> ArrayList&lt;&gt;();</div><div class="line">        Mat hierarchy = <span class="keyword">new</span> Mat();</div><div class="line">        Imgproc.findContours(cannyOutput, contours, hierarchy, Imgproc.RETR_TREE, Imgproc.CHAIN_APPROX_SIMPLE);</div><div class="line"></div><div class="line">        MatOfPoint2f[] contoursPoly  = <span class="keyword">new</span> MatOfPoint2f[contours.size()];</div><div class="line">        <a class="code" href="../../dc/d84/group__core__basic.html#ga11d95de507098e90bad732b9345402e8">Rect</a>[] boundRect = <span class="keyword">new</span> <a class="code" href="../../dc/d84/group__core__basic.html#ga11d95de507098e90bad732b9345402e8">Rect</a>[contours.size()];</div><div class="line">        <a class="code" href="../../dc/d84/group__core__basic.html#ga1e83eafb2d26b3c93f09e8338bcab192">Point</a>[] centers = <span class="keyword">new</span> <a class="code" href="../../dc/d84/group__core__basic.html#ga1e83eafb2d26b3c93f09e8338bcab192">Point</a>[contours.size()];</div><div class="line">        <span class="keywordtype">float</span>[][] radius = <span class="keyword">new</span> <span class="keywordtype">float</span>[contours.size()][1];</div><div class="line"></div><div class="line">        <span class="keywordflow">for</span> (<span class="keywordtype">int</span> i = 0; i &lt; contours.size(); i++) {</div><div class="line">            contoursPoly[i] = <span class="keyword">new</span> MatOfPoint2f();</div><div class="line">            Imgproc.approxPolyDP(<span class="keyword">new</span> MatOfPoint2f(contours.get(i).toArray()), contoursPoly[i], 3, <span class="keyword">true</span>);</div><div class="line">            boundRect[i] = Imgproc.boundingRect(<span class="keyword">new</span> MatOfPoint(contoursPoly[i].toArray()));</div><div class="line">            centers[i] = <span class="keyword">new</span> <a class="code" href="../../dc/d84/group__core__basic.html#ga1e83eafb2d26b3c93f09e8338bcab192">Point</a>();</div><div class="line">            Imgproc.minEnclosingCircle(contoursPoly[i], centers[i], radius[i]);</div><div class="line">        }</div><div class="line"></div><div class="line">        Mat drawing = Mat.<a class="code" href="../../d3/d63/classcv_1_1Mat.html#a0b57b6a326c8876d944d188a46e0f556">zeros</a>(cannyOutput.size(), CvType.CV_8UC3);</div><div class="line">        List&lt;MatOfPoint&gt; contoursPolyList = <span class="keyword">new</span> ArrayList&lt;&gt;(contoursPoly.length);</div><div class="line">        <span class="keywordflow">for</span> (MatOfPoint2f poly : contoursPoly) {</div><div class="line">            contoursPolyList.add(<span class="keyword">new</span> MatOfPoint(poly.toArray()));</div><div class="line">        }</div><div class="line"></div><div class="line">        <span class="keywordflow">for</span> (<span class="keywordtype">int</span> i = 0; i &lt; contours.size(); i++) {</div><div class="line">            <a class="code" href="../../dc/d84/group__core__basic.html#ga599fe92e910c027be274233eccad7beb">Scalar</a> color = <span class="keyword">new</span> <a class="code" href="../../dc/d84/group__core__basic.html#ga599fe92e910c027be274233eccad7beb">Scalar</a>(rng.nextInt(256), rng.nextInt(256), rng.nextInt(256));</div><div class="line">            Imgproc.drawContours(drawing, contoursPolyList, i, color);</div><div class="line">            Imgproc.rectangle(drawing, boundRect[i].tl(), boundRect[i].br(), color, 2);</div><div class="line">            Imgproc.circle(drawing, centers[i], (<span class="keywordtype">int</span>) radius[i][0], color, 2);</div><div class="line">        }</div><div class="line"></div><div class="line">        imgContoursLabel.setIcon(<span class="keyword">new</span> ImageIcon(HighGui.toBufferedImage(drawing)));</div><div class="line">        frame.repaint();</div><div class="line">    }</div><div class="line">}</div><div class="line"></div><div class="line"><span class="keyword">public</span> <span class="keyword">class </span>GeneralContoursDemo1 {</div><div class="line">    <span class="keyword">public</span> <span class="keyword">static</span> <span class="keywordtype">void</span> main(<a class="code" href="../../dc/d84/group__core__basic.html#ga1f6634802eeadfd7245bc75cf3e216c2">String</a>[] args) {</div><div class="line">        <span class="comment">// Load the native OpenCV library</span></div><div class="line">        System.loadLibrary(Core.NATIVE_LIBRARY_NAME);</div><div class="line"></div><div class="line">        <span class="comment">// Schedule a job for the event dispatch thread:</span></div><div class="line">        <span class="comment">// creating and showing this application&#39;s GUI.</span></div><div class="line">        javax.swing.SwingUtilities.invokeLater(<span class="keyword">new</span> Runnable() {</div><div class="line">            @Override</div><div class="line">            <span class="keyword">public</span> <span class="keywordtype">void</span> run() {</div><div class="line">                <span class="keyword">new</span> GeneralContours1(args);</div><div class="line">            }</div><div class="line">        });</div><div class="line">    }</div><div class="line">}</div></div><!-- fragment -->  </div>  <div class='newInnerHTML' title='python' style='display: none;'>Python</div><div class='toggleable_div label_python' style='display: none;'><p> This tutorial code's is shown lines below. You can also download it from <a href="https://github.com/opencv/opencv/tree/master/samples/python/tutorial_code/ShapeDescriptors/bounding_rects_circles/generalContours_demo1.py">here</a> </p><div class="fragment"><div class="line"><span class="keyword">from</span> __future__ <span class="keyword">import</span> print_function</div><div class="line"><span class="keyword">import</span> cv2 <span class="keyword">as</span> cv</div><div class="line"><span class="keyword">import</span> numpy <span class="keyword">as</span> np</div><div class="line"><span class="keyword">import</span> argparse</div><div class="line"><span class="keyword">import</span> random <span class="keyword">as</span> rng</div><div class="line"></div><div class="line">rng.seed(12345)</div><div class="line"></div><div class="line"><span class="keyword">def </span>thresh_callback(val):</div><div class="line">    threshold = val</div><div class="line"></div><div class="line">    </div><div class="line">    canny_output = <a class="code" href="../../dd/d1a/group__imgproc__feature.html#ga2a671611e104c093843d7b7fc46d24af">cv.Canny</a>(src_gray, threshold, threshold * 2)</div><div class="line">    </div><div class="line"></div><div class="line">    </div><div class="line">    contours, _ = <a class="code" href="../../d3/dc0/group__imgproc__shape.html#gae4156f04053c44f886e387cff0ef6e08">cv.findContours</a>(canny_output, cv.RETR_TREE, cv.CHAIN_APPROX_SIMPLE)</div><div class="line">    </div><div class="line"></div><div class="line">    </div><div class="line">    contours_poly = [<span class="keywordtype">None</span>]*len(contours)</div><div class="line">    boundRect = [<span class="keywordtype">None</span>]*len(contours)</div><div class="line">    centers = [<span class="keywordtype">None</span>]*len(contours)</div><div class="line">    radius = [<span class="keywordtype">None</span>]*len(contours)</div><div class="line">    <span class="keywordflow">for</span> i, c <span class="keywordflow">in</span> enumerate(contours):</div><div class="line">        contours_poly[i] = <a class="code" href="../../d3/dc0/group__imgproc__shape.html#ga0012a5fdaea70b8a9970165d98722b4c">cv.approxPolyDP</a>(c, 3, <span class="keyword">True</span>)</div><div class="line">        boundRect[i] = <a class="code" href="../../d3/dc0/group__imgproc__shape.html#ga103fcbda2f540f3ef1c042d6a9b35ac7">cv.boundingRect</a>(contours_poly[i])</div><div class="line">        centers[i], radius[i] = <a class="code" href="../../d3/dc0/group__imgproc__shape.html#ga8ce13c24081bbc7151e9326f412190f1">cv.minEnclosingCircle</a>(contours_poly[i])</div><div class="line">    </div><div class="line"></div><div class="line">    </div><div class="line">    drawing = np.zeros((canny_output.shape[0], canny_output.shape[1], 3), dtype=np.uint8)</div><div class="line">    </div><div class="line"></div><div class="line">    </div><div class="line">    <span class="keywordflow">for</span> i <span class="keywordflow">in</span> range(len(contours)):</div><div class="line">        color = (rng.randint(0,256), rng.randint(0,256), rng.randint(0,256))</div><div class="line">        <a class="code" href="../../d6/d6e/group__imgproc__draw.html#ga746c0625f1781f1ffc9056259103edbc">cv.drawContours</a>(drawing, contours_poly, i, color)</div><div class="line">        <a class="code" href="../../d6/d6e/group__imgproc__draw.html#gac865734d137287c0afb7682ff7b3db23">cv.rectangle</a>(drawing, (int(boundRect[i][0]), int(boundRect[i][1])), \</div><div class="line">          (int(boundRect[i][0]+boundRect[i][2]), int(boundRect[i][1]+boundRect[i][3])), color, 2)</div><div class="line">        <a class="code" href="../../d6/d6e/group__imgproc__draw.html#gaf10604b069374903dbd0f0488cb43670">cv.circle</a>(drawing, (int(centers[i][0]), int(centers[i][1])), int(radius[i]), color, 2)</div><div class="line">    </div><div class="line"></div><div class="line">    </div><div class="line">    <a class="code" href="../../df/d24/group__highgui__opengl.html#gaae7e90aa3415c68dba22a5ff2cefc25d">cv.imshow</a>(<span class="stringliteral">&#39;Contours&#39;</span>, drawing)</div><div class="line">    </div><div class="line"></div><div class="line"></div><div class="line">parser = argparse.ArgumentParser(description=<span class="stringliteral">&#39;Code for Creating Bounding boxes and circles for contours tutorial.&#39;</span>)</div><div class="line">parser.add_argument(<span class="stringliteral">&#39;--input&#39;</span>, help=<span class="stringliteral">&#39;Path to input image.&#39;</span>, default=<span class="stringliteral">&#39;stuff.jpg&#39;</span>)</div><div class="line">args = parser.parse_args()</div><div class="line"></div><div class="line">src = <a class="code" href="../../d4/da8/group__imgcodecs.html#ga288b8b3da0892bd651fce07b3bbd3a56">cv.imread</a>(<a class="code" href="../../d6/dba/group__core__utils__samples.html#ga3a33b00033b46c698ff6340d95569c13">cv.samples.findFile</a>(args.input))</div><div class="line"><span class="keywordflow">if</span> src <span class="keywordflow">is</span> <span class="keywordtype">None</span>:</div><div class="line">    <a class="code" href="../../df/d57/namespacecv_1_1dnn.html#a701210a0203f2786cbfd04b2bd56da47">print</a>(<span class="stringliteral">&#39;Could not open or find the image:&#39;</span>, args.input)</div><div class="line">    exit(0)</div><div class="line"></div><div class="line"><span class="comment"># Convert image to gray and blur it</span></div><div class="line">src_gray = <a class="code" href="../../d8/d01/group__imgproc__color__conversions.html#ga397ae87e1288a81d2363b61574eb8cab">cv.cvtColor</a>(src, cv.COLOR_BGR2GRAY)</div><div class="line">src_gray = <a class="code" href="../../d4/d86/group__imgproc__filter.html#ga8c45db9afe636703801b0b2e440fce37">cv.blur</a>(src_gray, (3,3))</div><div class="line"></div><div class="line"></div><div class="line"></div><div class="line">source_window = <span class="stringliteral">&#39;Source&#39;</span></div><div class="line"><a class="code" href="../../d7/dfc/group__highgui.html#ga5afdf8410934fd099df85c75b2e0888b">cv.namedWindow</a>(source_window)</div><div class="line"><a class="code" href="../../df/d24/group__highgui__opengl.html#gaae7e90aa3415c68dba22a5ff2cefc25d">cv.imshow</a>(source_window, src)</div><div class="line"></div><div class="line">max_thresh = 255</div><div class="line">thresh = 100 <span class="comment"># initial threshold</span></div><div class="line"><a class="code" href="../../d7/dfc/group__highgui.html#gaf78d2155d30b728fc413803745b67a9b">cv.createTrackbar</a>(<span class="stringliteral">&#39;Canny thresh:&#39;</span>, source_window, thresh, max_thresh, thresh_callback)</div><div class="line">thresh_callback(thresh)</div><div class="line"></div><div class="line"></div><div class="line"><a class="code" href="../../d7/dfc/group__highgui.html#ga5628525ad33f52eab17feebcfba38bd7">cv.waitKey</a>()</div></div><!-- fragment -->  </div> <h2>Explanation </h2>
<p>The main function is rather simple, as follows from the comments we do the following:</p><ul>
<li>Open the image, convert it into grayscale and blur it to get rid of the noise.</li>
</ul>
 <div class='newInnerHTML' title='cpp' style='display: none;'>C++</div><div class='toggleable_div label_cpp' style='display: none;'> <div class="fragment"><div class="line">    CommandLineParser parser( argc, argv, <span class="stringliteral">&quot;{@input | stuff.jpg | input image}&quot;</span> );</div><div class="line">    Mat src = <a class="code" href="../../d4/da8/group__imgcodecs.html#ga288b8b3da0892bd651fce07b3bbd3a56">imread</a>( <a class="code" href="../../d6/dba/group__core__utils__samples.html#ga3a33b00033b46c698ff6340d95569c13">samples::findFile</a>( parser.get&lt;<a class="code" href="../../dc/d84/group__core__basic.html#ga1f6634802eeadfd7245bc75cf3e216c2">String</a>&gt;( <span class="stringliteral">&quot;@input&quot;</span> ) ) );</div><div class="line">    <span class="keywordflow">if</span>( src.empty() )</div><div class="line">    {</div><div class="line">        cout &lt;&lt; <span class="stringliteral">&quot;Could not open or find the image!\n&quot;</span> &lt;&lt; endl;</div><div class="line">        cout &lt;&lt; <span class="stringliteral">&quot;usage: &quot;</span> &lt;&lt; argv[0] &lt;&lt; <span class="stringliteral">&quot; &lt;Input image&gt;&quot;</span> &lt;&lt; endl;</div><div class="line">        <span class="keywordflow">return</span> -1;</div><div class="line">    }</div><div class="line"></div><div class="line">    <a class="code" href="../../d8/d01/group__imgproc__color__conversions.html#ga397ae87e1288a81d2363b61574eb8cab">cvtColor</a>( src, src_gray, <a class="code" href="../../d8/d01/group__imgproc__color__conversions.html#gga4e0972be5de079fed4e3a10e24ef5ef0a353a4b8db9040165db4dacb5bcefb6ea">COLOR_BGR2GRAY</a> );</div><div class="line">    <a class="code" href="../../d4/d86/group__imgproc__filter.html#ga8c45db9afe636703801b0b2e440fce37">blur</a>( src_gray, src_gray, <a class="code" href="../../dc/d84/group__core__basic.html#ga346f563897249351a34549137c8532a0">Size</a>(3,3) );</div></div><!-- fragment --> </div>  <div class='newInnerHTML' title='java' style='display: none;'>Java</div><div class='toggleable_div label_java' style='display: none;'> <div class="fragment"><div class="line">        <a class="code" href="../../dc/d84/group__core__basic.html#ga1f6634802eeadfd7245bc75cf3e216c2">String</a> filename = args.length &gt; 0 ? args[0] : <span class="stringliteral">&quot;../data/stuff.jpg&quot;</span>;</div><div class="line">        Mat src = Imgcodecs.imread(filename);</div><div class="line">        <span class="keywordflow">if</span> (src.empty()) {</div><div class="line">            System.err.println(<span class="stringliteral">&quot;Cannot read image: &quot;</span> + filename);</div><div class="line">            System.exit(0);</div><div class="line">        }</div><div class="line"></div><div class="line">        Imgproc.cvtColor(src, srcGray, Imgproc.COLOR_BGR2GRAY);</div><div class="line">        Imgproc.blur(srcGray, srcGray, <span class="keyword">new</span> <a class="code" href="../../dc/d84/group__core__basic.html#ga346f563897249351a34549137c8532a0">Size</a>(3, 3));</div></div><!-- fragment --> </div>  <div class='newInnerHTML' title='python' style='display: none;'>Python</div><div class='toggleable_div label_python' style='display: none;'> <div class="fragment"><div class="line"><span class="comment"># Load source image</span></div><div class="line">parser = argparse.ArgumentParser(description=<span class="stringliteral">&#39;Code for Creating Bounding boxes and circles for contours tutorial.&#39;</span>)</div><div class="line">parser.add_argument(<span class="stringliteral">&#39;--input&#39;</span>, help=<span class="stringliteral">&#39;Path to input image.&#39;</span>, default=<span class="stringliteral">&#39;stuff.jpg&#39;</span>)</div><div class="line">args = parser.parse_args()</div><div class="line"></div><div class="line">src = <a class="code" href="../../d4/da8/group__imgcodecs.html#ga288b8b3da0892bd651fce07b3bbd3a56">cv.imread</a>(<a class="code" href="../../d6/dba/group__core__utils__samples.html#ga3a33b00033b46c698ff6340d95569c13">cv.samples.findFile</a>(args.input))</div><div class="line"><span class="keywordflow">if</span> src <span class="keywordflow">is</span> <span class="keywordtype">None</span>:</div><div class="line">    <a class="code" href="../../df/d57/namespacecv_1_1dnn.html#a701210a0203f2786cbfd04b2bd56da47">print</a>(<span class="stringliteral">&#39;Could not open or find the image:&#39;</span>, args.input)</div><div class="line">    exit(0)</div><div class="line"></div><div class="line"><span class="comment"># Convert image to gray and blur it</span></div><div class="line">src_gray = <a class="code" href="../../d8/d01/group__imgproc__color__conversions.html#ga397ae87e1288a81d2363b61574eb8cab">cv.cvtColor</a>(src, cv.COLOR_BGR2GRAY)</div><div class="line">src_gray = <a class="code" href="../../d4/d86/group__imgproc__filter.html#ga8c45db9afe636703801b0b2e440fce37">cv.blur</a>(src_gray, (3,3))</div></div><!-- fragment --> </div> <ul>
<li>Create a window with header "Source" and display the source file in it.</li>
</ul>
 <div class='newInnerHTML' title='cpp' style='display: none;'>C++</div><div class='toggleable_div label_cpp' style='display: none;'> <div class="fragment"><div class="line">    <span class="keyword">const</span> <span class="keywordtype">char</span>* source_window = <span class="stringliteral">&quot;Source&quot;</span>;</div><div class="line">    <a class="code" href="../../d7/dfc/group__highgui.html#ga5afdf8410934fd099df85c75b2e0888b">namedWindow</a>( source_window );</div><div class="line">    <a class="code" href="../../d7/dfc/group__highgui.html#ga453d42fe4cb60e5723281a89973ee563">imshow</a>( source_window, src );</div></div><!-- fragment --> </div>  <div class='newInnerHTML' title='java' style='display: none;'>Java</div><div class='toggleable_div label_java' style='display: none;'> <div class="fragment"><div class="line">        <span class="comment">// Create and set up the window.</span></div><div class="line">        frame = <span class="keyword">new</span> JFrame(<span class="stringliteral">&quot;Creating Bounding boxes and circles for contours demo&quot;</span>);</div><div class="line">        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);</div><div class="line">        <span class="comment">// Set up the content pane.</span></div><div class="line">        Image img = HighGui.toBufferedImage(src);</div><div class="line">        addComponentsToPane(frame.getContentPane(), img);</div></div><!-- fragment --> </div>  <div class='newInnerHTML' title='python' style='display: none;'>Python</div><div class='toggleable_div label_python' style='display: none;'> <div class="fragment"><div class="line"><span class="comment"># Create Window</span></div><div class="line">source_window = <span class="stringliteral">&#39;Source&#39;</span></div><div class="line"><a class="code" href="../../d7/dfc/group__highgui.html#ga5afdf8410934fd099df85c75b2e0888b">cv.namedWindow</a>(source_window)</div><div class="line"><a class="code" href="../../df/d24/group__highgui__opengl.html#gaae7e90aa3415c68dba22a5ff2cefc25d">cv.imshow</a>(source_window, src)</div></div><!-- fragment --> </div> <ul>
<li>Create a trackbar on the <code>source_window</code> and assign a callback function to it. In general callback functions are used to react to some kind of signal, in our case it's trackbar's state change. Explicit one-time call of <code>thresh_callback</code> is necessary to display the "Contours" window simultaniously with the "Source" window.</li>
</ul>
 <div class='newInnerHTML' title='cpp' style='display: none;'>C++</div><div class='toggleable_div label_cpp' style='display: none;'> <div class="fragment"><div class="line">    <span class="keyword">const</span> <span class="keywordtype">int</span> max_thresh = 255;</div><div class="line">    <a class="code" href="../../d7/dfc/group__highgui.html#gaf78d2155d30b728fc413803745b67a9b">createTrackbar</a>( <span class="stringliteral">&quot;Canny thresh:&quot;</span>, source_window, &amp;thresh, max_thresh, thresh_callback );</div><div class="line">    thresh_callback( 0, 0 );</div></div><!-- fragment --> </div>  <div class='newInnerHTML' title='java' style='display: none;'>Java</div><div class='toggleable_div label_java' style='display: none;'> <div class="fragment"><div class="line">        sliderPanel.add(<span class="keyword">new</span> JLabel(<span class="stringliteral">&quot;Canny threshold: &quot;</span>));</div><div class="line">        JSlider slider = <span class="keyword">new</span> JSlider(0, MAX_THRESHOLD, threshold);</div><div class="line">        slider.setMajorTickSpacing(20);</div><div class="line">        slider.setMinorTickSpacing(10);</div><div class="line">        slider.setPaintTicks(<span class="keyword">true</span>);</div><div class="line">        slider.setPaintLabels(<span class="keyword">true</span>);</div><div class="line">        slider.addChangeListener(<span class="keyword">new</span> ChangeListener() {</div><div class="line">            @Override</div><div class="line">            <span class="keyword">public</span> <span class="keywordtype">void</span> stateChanged(ChangeEvent e) {</div><div class="line">                JSlider source = (JSlider) e.getSource();</div><div class="line">                threshold = source.getValue();</div><div class="line">                update();</div><div class="line">            }</div><div class="line">        });</div></div><!-- fragment --> </div>  <div class='newInnerHTML' title='python' style='display: none;'>Python</div><div class='toggleable_div label_python' style='display: none;'> <div class="fragment"><div class="line">max_thresh = 255</div><div class="line">thresh = 100 <span class="comment"># initial threshold</span></div><div class="line"><a class="code" href="../../d7/dfc/group__highgui.html#gaf78d2155d30b728fc413803745b67a9b">cv.createTrackbar</a>(<span class="stringliteral">&#39;Canny thresh:&#39;</span>, source_window, thresh, max_thresh, thresh_callback)</div><div class="line">thresh_callback(thresh)</div></div><!-- fragment --> </div> <p>The callback function does all the interesting job.</p>
<ul>
<li>Use <a class="el" href="../../dd/d1a/group__imgproc__feature.html#ga04723e007ed888ddf11d9ba04e2232de">cv::Canny</a> to detect edges in the images.</li>
</ul>
 <div class='newInnerHTML' title='cpp' style='display: none;'>C++</div><div class='toggleable_div label_cpp' style='display: none;'> <div class="fragment"><div class="line">    Mat canny_output;</div><div class="line">    <a class="code" href="../../dd/d1a/group__imgproc__feature.html#ga04723e007ed888ddf11d9ba04e2232de">Canny</a>( src_gray, canny_output, thresh, thresh*2 );</div></div><!-- fragment --> </div>  <div class='newInnerHTML' title='java' style='display: none;'>Java</div><div class='toggleable_div label_java' style='display: none;'> <div class="fragment"><div class="line">        Mat cannyOutput = <span class="keyword">new</span> Mat();</div><div class="line">        Imgproc.Canny(srcGray, cannyOutput, threshold, threshold * 2);</div></div><!-- fragment --> </div>  <div class='newInnerHTML' title='python' style='display: none;'>Python</div><div class='toggleable_div label_python' style='display: none;'> <div class="fragment"><div class="line">    <span class="comment"># Detect edges using Canny</span></div><div class="line">    canny_output = <a class="code" href="../../dd/d1a/group__imgproc__feature.html#ga2a671611e104c093843d7b7fc46d24af">cv.Canny</a>(src_gray, threshold, threshold * 2)</div></div><!-- fragment --> </div> <ul>
<li>Finds contours and saves them to the vectors <code>contour</code> and <code>hierarchy</code>.</li>
</ul>
 <div class='newInnerHTML' title='cpp' style='display: none;'>C++</div><div class='toggleable_div label_cpp' style='display: none;'> <div class="fragment"><div class="line">    vector&lt;vector&lt;Point&gt; &gt; contours;</div><div class="line">    <a class="code" href="../../d3/dc0/group__imgproc__shape.html#gadf1ad6a0b82947fa1fe3c3d497f260e0">findContours</a>( canny_output, contours, <a class="code" href="../../d3/dc0/group__imgproc__shape.html#gga819779b9857cc2f8601e6526a3a5bc71ab10df56aed56c89a026580adc9431f58">RETR_TREE</a>, <a class="code" href="../../d3/dc0/group__imgproc__shape.html#gga4303f45752694956374734a03c54d5ffa5f2883048e654999209f88ba04c302f5">CHAIN_APPROX_SIMPLE</a> );</div></div><!-- fragment --> </div>  <div class='newInnerHTML' title='java' style='display: none;'>Java</div><div class='toggleable_div label_java' style='display: none;'> <div class="fragment"><div class="line">        List&lt;MatOfPoint&gt; contours = <span class="keyword">new</span> ArrayList&lt;&gt;();</div><div class="line">        Mat hierarchy = <span class="keyword">new</span> Mat();</div><div class="line">        Imgproc.findContours(cannyOutput, contours, hierarchy, Imgproc.RETR_TREE, Imgproc.CHAIN_APPROX_SIMPLE);</div></div><!-- fragment --> </div>  <div class='newInnerHTML' title='python' style='display: none;'>Python</div><div class='toggleable_div label_python' style='display: none;'> <div class="fragment"><div class="line">    <span class="comment"># Find contours</span></div><div class="line">    contours, _ = <a class="code" href="../../d3/dc0/group__imgproc__shape.html#gae4156f04053c44f886e387cff0ef6e08">cv.findContours</a>(canny_output, cv.RETR_TREE, cv.CHAIN_APPROX_SIMPLE)</div></div><!-- fragment --> </div> <ul>
<li>For every found contour we now apply approximation to polygons with accuracy +-3 and stating that the curve must be closed. After that we find a bounding rect for every polygon and save it to <code>boundRect</code>. At last we find a minimum enclosing circle for every polygon and save it to <code>center</code> and <code>radius</code> vectors.</li>
</ul>
 <div class='newInnerHTML' title='cpp' style='display: none;'>C++</div><div class='toggleable_div label_cpp' style='display: none;'> <div class="fragment"><div class="line">    vector&lt;vector&lt;Point&gt; &gt; contours_poly( contours.size() );</div><div class="line">    vector&lt;Rect&gt; boundRect( contours.size() );</div><div class="line">    vector&lt;Point2f&gt;centers( contours.size() );</div><div class="line">    vector&lt;float&gt;radius( contours.size() );</div><div class="line"></div><div class="line">    <span class="keywordflow">for</span>( <span class="keywordtype">size_t</span> i = 0; i &lt; contours.size(); i++ )</div><div class="line">    {</div><div class="line">        <a class="code" href="../../d3/dc0/group__imgproc__shape.html#ga0012a5fdaea70b8a9970165d98722b4c">approxPolyDP</a>( contours[i], contours_poly[i], 3, <span class="keyword">true</span> );</div><div class="line">        boundRect[i] = <a class="code" href="../../d3/dc0/group__imgproc__shape.html#ga103fcbda2f540f3ef1c042d6a9b35ac7">boundingRect</a>( contours_poly[i] );</div><div class="line">        <a class="code" href="../../d3/dc0/group__imgproc__shape.html#ga8ce13c24081bbc7151e9326f412190f1">minEnclosingCircle</a>( contours_poly[i], centers[i], radius[i] );</div><div class="line">    }</div></div><!-- fragment --> </div>  <div class='newInnerHTML' title='java' style='display: none;'>Java</div><div class='toggleable_div label_java' style='display: none;'> <div class="fragment"><div class="line">        MatOfPoint2f[] contoursPoly  = <span class="keyword">new</span> MatOfPoint2f[contours.size()];</div><div class="line">        <a class="code" href="../../dc/d84/group__core__basic.html#ga11d95de507098e90bad732b9345402e8">Rect</a>[] boundRect = <span class="keyword">new</span> <a class="code" href="../../dc/d84/group__core__basic.html#ga11d95de507098e90bad732b9345402e8">Rect</a>[contours.size()];</div><div class="line">        <a class="code" href="../../dc/d84/group__core__basic.html#ga1e83eafb2d26b3c93f09e8338bcab192">Point</a>[] centers = <span class="keyword">new</span> <a class="code" href="../../dc/d84/group__core__basic.html#ga1e83eafb2d26b3c93f09e8338bcab192">Point</a>[contours.size()];</div><div class="line">        <span class="keywordtype">float</span>[][] radius = <span class="keyword">new</span> <span class="keywordtype">float</span>[contours.size()][1];</div><div class="line"></div><div class="line">        <span class="keywordflow">for</span> (<span class="keywordtype">int</span> i = 0; i &lt; contours.size(); i++) {</div><div class="line">            contoursPoly[i] = <span class="keyword">new</span> MatOfPoint2f();</div><div class="line">            Imgproc.approxPolyDP(<span class="keyword">new</span> MatOfPoint2f(contours.get(i).toArray()), contoursPoly[i], 3, <span class="keyword">true</span>);</div><div class="line">            boundRect[i] = Imgproc.boundingRect(<span class="keyword">new</span> MatOfPoint(contoursPoly[i].toArray()));</div><div class="line">            centers[i] = <span class="keyword">new</span> <a class="code" href="../../dc/d84/group__core__basic.html#ga1e83eafb2d26b3c93f09e8338bcab192">Point</a>();</div><div class="line">            Imgproc.minEnclosingCircle(contoursPoly[i], centers[i], radius[i]);</div><div class="line">        }</div></div><!-- fragment --> </div>  <div class='newInnerHTML' title='python' style='display: none;'>Python</div><div class='toggleable_div label_python' style='display: none;'> <div class="fragment"><div class="line">    <span class="comment"># Approximate contours to polygons + get bounding rects and circles</span></div><div class="line">    contours_poly = [<span class="keywordtype">None</span>]*len(contours)</div><div class="line">    boundRect = [<span class="keywordtype">None</span>]*len(contours)</div><div class="line">    centers = [<span class="keywordtype">None</span>]*len(contours)</div><div class="line">    radius = [<span class="keywordtype">None</span>]*len(contours)</div><div class="line">    <span class="keywordflow">for</span> i, c <span class="keywordflow">in</span> enumerate(contours):</div><div class="line">        contours_poly[i] = <a class="code" href="../../d3/dc0/group__imgproc__shape.html#ga0012a5fdaea70b8a9970165d98722b4c">cv.approxPolyDP</a>(c, 3, <span class="keyword">True</span>)</div><div class="line">        boundRect[i] = <a class="code" href="../../d3/dc0/group__imgproc__shape.html#ga103fcbda2f540f3ef1c042d6a9b35ac7">cv.boundingRect</a>(contours_poly[i])</div><div class="line">        centers[i], radius[i] = <a class="code" href="../../d3/dc0/group__imgproc__shape.html#ga8ce13c24081bbc7151e9326f412190f1">cv.minEnclosingCircle</a>(contours_poly[i])</div></div><!-- fragment --> </div> <p>We found everything we need, all we have to do is to draw.</p>
<ul>
<li>Create new Mat of unsigned 8-bit chars, filled with zeros. It will contain all the drawings we are going to make (rects and circles).</li>
</ul>
 <div class='newInnerHTML' title='cpp' style='display: none;'>C++</div><div class='toggleable_div label_cpp' style='display: none;'> <div class="fragment"><div class="line">    Mat drawing = Mat::zeros( canny_output.size(), <a class="code" href="../../d1/d1b/group__core__hal__interface.html#ga88c4cd9de76f678f33928ef1e3f96047">CV_8UC3</a> );</div></div><!-- fragment --> </div>  <div class='newInnerHTML' title='java' style='display: none;'>Java</div><div class='toggleable_div label_java' style='display: none;'> <div class="fragment"><div class="line">        Mat drawing = Mat.zeros(cannyOutput.size(), CvType.CV_8UC3);</div></div><!-- fragment --> </div>  <div class='newInnerHTML' title='python' style='display: none;'>Python</div><div class='toggleable_div label_python' style='display: none;'> <div class="fragment"><div class="line">    drawing = np.zeros((canny_output.shape[0], canny_output.shape[1], 3), dtype=np.uint8)</div></div><!-- fragment --> </div> <ul>
<li>For every contour: pick a random color, draw the contour, the bounding rectangle and the minimal enclosing circle with it.</li>
</ul>
 <div class='newInnerHTML' title='cpp' style='display: none;'>C++</div><div class='toggleable_div label_cpp' style='display: none;'> <div class="fragment"><div class="line">    <span class="keywordflow">for</span>( <span class="keywordtype">size_t</span> i = 0; i&lt; contours.size(); i++ )</div><div class="line">    {</div><div class="line">        <a class="code" href="../../dc/d84/group__core__basic.html#ga599fe92e910c027be274233eccad7beb">Scalar</a> color = <a class="code" href="../../dc/d84/group__core__basic.html#ga599fe92e910c027be274233eccad7beb">Scalar</a>( rng.uniform(0, 256), rng.uniform(0,256), rng.uniform(0,256) );</div><div class="line">        <a class="code" href="../../d6/d6e/group__imgproc__draw.html#ga746c0625f1781f1ffc9056259103edbc">drawContours</a>( drawing, contours_poly, (<span class="keywordtype">int</span>)i, color );</div><div class="line">        <a class="code" href="../../d6/d6e/group__imgproc__draw.html#ga07d2f74cadcf8e305e810ce8eed13bc9">rectangle</a>( drawing, boundRect[i].tl(), boundRect[i].br(), color, 2 );</div><div class="line">        <a class="code" href="../../d9/db7/group__datasets__gr.html#gga610754124ced68d1f05760b5948fbb76a6f0d8b2d9e3e947b2a5c1eff9e81ee95">circle</a>( drawing, centers[i], (<span class="keywordtype">int</span>)radius[i], color, 2 );</div><div class="line">    }</div></div><!-- fragment --> </div>  <div class='newInnerHTML' title='java' style='display: none;'>Java</div><div class='toggleable_div label_java' style='display: none;'> <div class="fragment"><div class="line">        List&lt;MatOfPoint&gt; contoursPolyList = <span class="keyword">new</span> ArrayList&lt;&gt;(contoursPoly.length);</div><div class="line">        <span class="keywordflow">for</span> (MatOfPoint2f poly : contoursPoly) {</div><div class="line">            contoursPolyList.add(<span class="keyword">new</span> MatOfPoint(poly.toArray()));</div><div class="line">        }</div><div class="line"></div><div class="line">        <span class="keywordflow">for</span> (<span class="keywordtype">int</span> i = 0; i &lt; contours.size(); i++) {</div><div class="line">            <a class="code" href="../../dc/d84/group__core__basic.html#ga599fe92e910c027be274233eccad7beb">Scalar</a> color = <span class="keyword">new</span> <a class="code" href="../../dc/d84/group__core__basic.html#ga599fe92e910c027be274233eccad7beb">Scalar</a>(rng.nextInt(256), rng.nextInt(256), rng.nextInt(256));</div><div class="line">            Imgproc.drawContours(drawing, contoursPolyList, i, color);</div><div class="line">            Imgproc.rectangle(drawing, boundRect[i].tl(), boundRect[i].br(), color, 2);</div><div class="line">            Imgproc.circle(drawing, centers[i], (<span class="keywordtype">int</span>) radius[i][0], color, 2);</div><div class="line">        }</div></div><!-- fragment --> </div>  <div class='newInnerHTML' title='python' style='display: none;'>Python</div><div class='toggleable_div label_python' style='display: none;'> <div class="fragment"><div class="line">    <span class="comment"># Draw polygonal contour + bonding rects + circles</span></div><div class="line">    <span class="keywordflow">for</span> i <span class="keywordflow">in</span> range(len(contours)):</div><div class="line">        color = (rng.randint(0,256), rng.randint(0,256), rng.randint(0,256))</div><div class="line">        <a class="code" href="../../d6/d6e/group__imgproc__draw.html#ga746c0625f1781f1ffc9056259103edbc">cv.drawContours</a>(drawing, contours_poly, i, color)</div><div class="line">        <a class="code" href="../../d6/d6e/group__imgproc__draw.html#gac865734d137287c0afb7682ff7b3db23">cv.rectangle</a>(drawing, (int(boundRect[i][0]), int(boundRect[i][1])), \</div><div class="line">          (int(boundRect[i][0]+boundRect[i][2]), int(boundRect[i][1]+boundRect[i][3])), color, 2)</div><div class="line">        <a class="code" href="../../d6/d6e/group__imgproc__draw.html#gaf10604b069374903dbd0f0488cb43670">cv.circle</a>(drawing, (int(centers[i][0]), int(centers[i][1])), int(radius[i]), color, 2)</div></div><!-- fragment --> </div> <ul>
<li>Display the results: create a new window "Contours" and show everything we added to drawings on it.</li>
</ul>
 <div class='newInnerHTML' title='cpp' style='display: none;'>C++</div><div class='toggleable_div label_cpp' style='display: none;'> <div class="fragment"><div class="line">    <a class="code" href="../../d7/dfc/group__highgui.html#ga453d42fe4cb60e5723281a89973ee563">imshow</a>( <span class="stringliteral">&quot;Contours&quot;</span>, drawing );</div></div><!-- fragment --> </div>  <div class='newInnerHTML' title='java' style='display: none;'>Java</div><div class='toggleable_div label_java' style='display: none;'> <div class="fragment"><div class="line">        imgContoursLabel.setIcon(<span class="keyword">new</span> ImageIcon(HighGui.toBufferedImage(drawing)));</div><div class="line">        frame.repaint();</div></div><!-- fragment --> </div>  <div class='newInnerHTML' title='python' style='display: none;'>Python</div><div class='toggleable_div label_python' style='display: none;'> <div class="fragment"><div class="line">    <span class="comment"># Show in a window</span></div><div class="line">    <a class="code" href="../../df/d24/group__highgui__opengl.html#gaae7e90aa3415c68dba22a5ff2cefc25d">cv.imshow</a>(<span class="stringliteral">&#39;Contours&#39;</span>, drawing)</div></div><!-- fragment --> </div> <h2>Result </h2>
<p>Here it is: </p><div class="image">
<img src="../../Bounding_Rects_Circles_Source_Image.jpg" alt="Bounding_Rects_Circles_Source_Image.jpg"/>
</div>
 <div class="image">
<img src="../../Bounding_Rects_Circles_Result.jpg" alt="Bounding_Rects_Circles_Result.jpg"/>
</div>
 </div></div><!-- contents -->
<!-- HTML footer for doxygen 1.8.6-->
<!-- start footer part -->
<hr class="footer"/><address class="footer"><small>
Generated on Fri Apr 2 2021 11:36:36 for OpenCV by &#160;<a href="http://www.doxygen.org/index.html">
<img class="footer" src="../../doxygen.png" alt="doxygen"/>
</a> 1.8.13
</small></address>
<script type="text/javascript">
//<![CDATA[
addTutorialsButtons();
//]]>
</script>
</body>
</html>
